<?php

/**
 * project actions.
 *
 * @package    todoeet
 * @subpackage project
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12474 2008-10-31 10:41:27Z fabien $
 */
class projectActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
    //$this->project_list = $this->getRoute()->getObjects();
    $this->project_list = Doctrine::getTable('Project')->getTree()->fetchTree();
  }

  public function executeShow(sfWebRequest $request)
  {
    $this->project = $this->getRoute()->getObject();
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = new ProjectForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->form = new ProjectForm();

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $project = $this->getRoute()->getObject();
    
    $this->form = new ProjectForm($project);
    
    //******** set default val not working by now
    //if ($project->getNode()->hasParent())
    //  $this->form->setDefault('project_id', $project->getNode()->getParent()->getid());
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->form = new ProjectForm($this->getRoute()->getObject());

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->getRoute()->getObject()->delete();

    $this->redirect('project/index');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()));
    if ($form->isValid())
    {
      $parent = Doctrine::getTable('Project')->find($form['parent_id']->getValue());
      
      if ($form->getObject()->isNew())
      {
        $values = $form->getValues();
        unset($values['parent_id']);
      
        $new_project = new Project();
        $new_project->fromArray($values);

        $new_project->getNode()->insertAsLastChildOf($parent);
        
        $this->redirect('project/edit?id='.$new_project['id']);
      }
      else
      {
        $form->getObject()->getNode()->moveAsLastChildOf($parent);
        $this->redirect('project/edit?id='.$form->getObject()->getid());
      }
    }
  }
}
